#!/bin/bash

:<<EOF

我们先检查锁文件是否存在,   如果存在,   则打印一个消息并退出脚本。如果不存在,   则创建一个锁文件,   并设置一个trap,   在脚本退出时删除这个锁文件;

bash  /home/sky/Desktop/shell/chapter5-process-control-流程控制/lock.sh

EOF

#
# @param1  lock_file_path   锁的路径, 如果未指定, 则设置为 /tmp 目录
# @param2  lock_filename    锁的名称, 如果未指定, 则设置为 lock_file
#
function  LOCK(){

    lock_file_path=$1
    lock_filename=$2

    if [[ $lock_file_path == '' ]]; then
        lock_file_path='/tmp'
    fi

    if [[ $lock_filename == '' ]]; then
        lock_filename="lock_file"
    fi

    temp_file="${lock_file_path}/${lock_filename}"

    if [ -e "$temp_file" ]; then
        echo "The script has been  already running.   Do not  run it  repeatedly !   Please wait for the lock released. "
        exit 1
    fi
    touch "$temp_file"
    echo "lock  $temp_file  has been set ! "
    #catch  exit 事件 ,  当主脚本 退出时, 执行 trap 中的回调指令
    trap 'rm -f "$temp_file"  && echo "lock  ${temp_file}  has been released! "'   EXIT

}


